var Tool = require('tool/ztool.js');
var tool = new Tool();

var areapickJS = require('tool/areaPick/areaPick.js');
var airPortPickJS = require('tool/airPortPick/airPortPick.js');
var app = getApp()

Page({

  data: {
    loadError: false,
    loadError2: false,
    pageIndex: 1,
    list: [],
    listNullCar: [],
    date: [],
    dateTitle: [],
    /*页面配置 */
    winWidth: 0,
    winHeight: 0,
    // tab切换  
    currentTab: 0,
    inputShowed: false,
    inputShowed2: true,
    inputVal: "",
    carType: ['业务', '空车'],
    seatNumArr: [],
    //地区选择器数据
    areaData: {
      current: 0,
      province: [],
      city: [],
      region: [],
      town: [],
      provinceObjects: [],
      cityObjects: [],
      regionObjects: [],
      townObjects: [],
      starAreaSelectedStr: '请选择省市区',
      endAreaSelectedStr: '请选择省市区',
      maskVisual: 'hidden',
      provinceName: '请选择',
      isDefault: true,
    },
    //机场选择器数据
    airPortpickData: {
      maskVisualAir: 'hidden'
    }
  },

  onLoad: function (options) {
    var that = this;
    /* 获取系统信息*/
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });

    //2017/3/11改 start 由于此界面不是程序打开之后直接加载的界面，因此在执行登录方法之前先判断是否已经登录过
    var appInstance = getApp();
    if(appInstance.globalData.hasLogin){

        //--start-小朱的代码
        var data = {
            pageSize: 20,
            PageIndex: this.data.pageIndex
        }
        loadDataHui(this, data);
        loadDataNullCar(this);
        //--end

    }else{
        login(this,appInstance);
    }
    //-------------END
  },

  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
      var appInstance = getApp();
      console.log(appInstance);
      if(appInstance.globalData.hasLogin){
          //在数据重置之前判断，首次登录是否为true
          if(this.data.firstLogin){

              //--start-小朱的代码
              var data = {
                  pageSize: 20,
                  PageIndex: this.data.pageIndex
              }
              loadDataHui(this, data);
              loadDataNullCar(this);
              //--end
          }else{
              var phone2 = wx.getStorageSync('username');
              if(phone2 != this.data.phone){

                  //将保存的phone重新赋值为此时本地所保存的phone
                  this.data.phone = phone2;

                  //小朱的代码
                  var data = {
                      pageSize: 20,
                      PageIndex: this.data.pageIndex
                  }
                  loadDataHui(this, data);
                  loadDataNullCar(this);
              }
          }

          this.setData({
              firstLogin: false,
              isLogin: false,
              loginError: false
          });
      }else{
          if(appInstance.globalData.hasLogout){
              this.setData({
                  firstLogin: true,
                  isLogin: false,
                  loginError: false
              });
          }
      }
  },

  //下拉刷新
  onPullDownRefresh: function () {
    this.setData({
      pageIndex: 1
    })
    // //小朱的代码
    // var data = {
    //     pageSize: 20,
    //     PageIndex: this.data.pageIndex
    // }
    // loadDataHui(this, data);
    // loadDataNullCar(this);
    this.onload();
  },

  //上拉加载更多
  onReachBottom: function (event) {
    var appInstance = getApp();
    if(!appInstance.globalData.hasLogin) return;

    showLoad();
    this.setData({

      pageIndex: this.data.pageIndex + 1
    })
    this.onLoad();
  },

  /*点击tab切换*/
  swichNav: function (e) {
    var that = this;
    if (this.data.currentTab == e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },

  //拨打电话
  callPhone: function (e) {
    if (e.currentTarget.dataset.phone == "") {
      wx.showToast({
        title: '号码为空',
        icon: 'none',
      });
      return;
    }
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone,
      success: function (res) {
        console.log('拨打电话成功');
      }
    })
  },

  //展示更多
  showInput: function () {
    this.setData({
      inputShowed: true,
      inputShowed2: false
    })
    var seatNumArr = new Array();
    for (var i = 4; i < 70; i++) {
      seatNumArr.push(i);
    }
    console.log('座位数数组', seatNumArr);
    this.setData({
      seatNumArr: seatNumArr
    })
  },

  hideInput: function () {
    console.log('hidden');
    this.setData({
      inputShowed: false
    });
  },

  bindDateChange: function (e) {
    console.log('弹出');
    if (e.currentTarget.dataset.dataSource) {
      this.setData(JSON.parse('{"' + e.currentTarget.dataset.name + '":"' + e.currentTarget.dataset.dataSource[e.detail.value] + '"}'))
    } else {
      this.setData(JSON.parse('{"' + e.currentTarget.dataset.name + '":"' + e.detail.value + '"}'));
    }
  },

  //地区选择
  areaPickTap: function (e) {
    areapickJS.areaPickDoor(this, e);
  },

  //机场选择
  //先区别起始机场，和目的机场 根据id获取机场列表，更新机场列表，
  airPortPick: function (e) {
    airPortPickJS.airPortPickDoor(this, e);
  },

//取消
  cancel: function (e){
    this.setData({
      inputShowed2: true,
      inputShowed: false
    })
  },

  //机场选择点击事件
  airPortTapped: function (e) {
    console.log(e);
    var index = e.currentTarget.dataset.index;
    var airPortName = this.data.airPortpickData.AirPortArr[index];
    var key = this.data.airPortType;
    console.log('key', key, this.data);
    this.setData(JSON.parse('{"' + key + '":"' + airPortName + '"}'));
    airPortPickJS.cascadeDismissAir(this, e);
  },

  //清除文本框数据
  clearDate: function (e) {
    console.log(this.data);
    if(e.currentTarget.dataset.dataName == 'starPlaceSelectedStr'){
      delete this.data.starPlaceSelectedStrCity;
      delete this.data.starPlaceSelectedStrProvince;
    }
    if(e.currentTarget.dataset.dataName == 'endPlaceSelectedStr'){
      delete this.data.endPlaceSelectedStrCity;
      delete this.data.endPlaceSelectedStrProvince;
    }
    var key = e.currentTarget.dataset.dataName;
    this.setData(JSON.parse('{"' + key + '":"' + '' + '"}'))
  },
  //筛选数据
  screen: function (e) {
    this.setData({
          list:[],
          inputShowed: false
      });
    this.data.pageIndex = 1;
    var data = {
      pageSize: 20,
      PageIndex: this.data.pageIndex,
    };
    if(this.data.starDate){
      var STime  = this.data.starDate;
      if(this.data.starTime){
        STime = STime+' '+this.data.starTime;
      }
      data.STime = STime;
    }
    if(this.data.endDate){
      var ETime  = this.data.starDate;
      if(this.data.starTime){
        ETime = ETime+' '+this.data.endTime;
      }
      data.ETime = ETime;
    }
    var starPlaceArr = new Array();
    var endPlaceArr = new Array();
    if (this.data.starPlaceSelectedStr) {
      var starPlace = this.data.starPlaceSelectedStr;
      starPlaceArr = starPlace.split(' ');
      data.SProvince = starPlaceArr[0];
      data.SCity = starPlaceArr[1];
      data.SCounty = starPlaceArr[2];
    }
    if (this.data.endPlaceSelectedStr) {
      var endPlace = this.data.endPlaceSelectedStr;
      endPlaceArr = endPlace.split(' ');
      data.EProvince = endPlaceArr[0];
      data.ECity = endPlaceArr[1];
      data.ECounty = endPlaceArr[2];
    }
    if(this.data.starAirPort){
      data.SAir = this.data.starAirPort;
    }
    if(this.data.endAirPort){
       data.EAir = this.data.endAirPort;
    }
    if(this.data.screenCarType){
      data.Propetry = this.data.screenCarType;
    }
    console.log('data',data);
    loadDataHui(this, data);
  },
  handletouchmove : function(){
    console.log('滑动');
  },

  //----------start 2017/3/11
  goLogin(){
    wx.navigateTo({
        url: '../login/login',
    })
  }
  //---------end

})
//************************************(page外函数) **********************/

//加载慧订车列表数据
function loadDataHui(that, data) {
  console.log('load');
  wx.showToast({
    title: '正在加载...',
    icon: 'loading',
    duration: 10000
  });
  wx.request({
    url: 'https://www.lanshuicar.com/Server/SupplyAndUseCars.ashx',
    data: data,
    method: 'GET',
    success: function (res) {
      wx.hideToast();
      var newJson = tool.getRegularJson(res.data);
      
      var list = that.data.list;
      list = list.concat(newJson.data);
      var starArr = new Array();
      var endArr = new Array();
      for (var i = 0; i < list.length; i++) {
        var info = list[i];
        starArr.push(info.mUpTime.substr(0, 10));
        endArr.push(info.mDnTime.substr(0, 10));
      }
      that.setData({
        list: list,
        starArr: starArr,
        endArr: endArr,
        loadError: false
      })
      console.log('获取列表',newJson);

    },
    fail: function () {
      wx.hideToast();
      that.setData({
        loadError: true
      });
    }
  })
}

//加载空车列表数据
function loadDataNullCar(that) {
  wx.showToast({
    title: '正在加载...',
    icon: 'loading',
    duration: 10000
  });
  wx.request({
    url: 'https://www.lanshuicar.com/Server/EmptyCarInfo.ashx',
    data: {
      PageIndex: 1,
      PageSize: 20,
      method: 3,
    },
    method: 'GET',
    success: function (res) {
      wx.hideToast();
      dealListData(res, that);

      //2017/3/21
      wx.stopPullDownRefresh();
    },
    fail: function () {
      wx.hideToast();
      that.setData({
        loadError2: true
      });
    }
  })
}

function navigateTo() {
  wx.navigateTo({
    url: '/pages/composite/compositeDetail/compositeDetail',
    success: function (res) {
      // success
    },
    fail: function () {
      // fail
    },
    complete: function () {
      // complete
    }
  })
}

//处理空车列表数据
function dealListData(res, that) {
  var arr = res.data.data;  //所有空车信息
  var date = new Array();   //用来存放时间信息，例如：上午：车辆数 下午：车辆数 日期：2016-8-3
  var dateTitle = new Array();  //用来存放日期信息，0坐标存放月份 例如：['二月','3','4'.....]
  for (var i = 0; i < arr.length; i++) {
    date.push(arr[i].time)
    var timeArr = arr[i].time;
    var tempArr = new Array();
    for (var j = 0; j < timeArr.length; j++) {
      var time = timeArr[j].time; //时间： 例如 1994-12-9 00:00：00
      if (j == 0) {
        //数组下标0插入月份 取出月份
        var month = time.split("-")[1];
        var monthsArr = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
        month = monthsArr[month - 1];
        tempArr.push(month);
      }
      //添加日期
      var day = time.split("-")[2];
      var oneDate = day.split(" ")[0]
      tempArr.push(oneDate);
    }
    dateTitle.push(tempArr);
  }
  that.setData({
    listNullCar: arr,
    loadError2: false,
    date: date,
    dateTitle: dateTitle,
  })
}
function showLoad() {
  wx.showToast({
    title: '正在加载...',
    icon: 'loading',
    duration: 10000
  });

}


//---------start 2017/3/11
function login(that,appInstance){
        
    //在在App打开时，从存储中取出username和password，并执行登录方法，登录成功，就将全局变量中的hasLogin置为true，否则为false

    var username = wx.getStorageSync('username');
    var password = wx.getStorageSync('password');
    console.log('app.js','login start');
    console.log('app.js',username);
    if(username && password){
        that.setData({
            firstLogin: false,
            isLogin: true,
            loginError: false
        });

        wx.request({
            url: 'https://www.lanshuicar.com/Server/LoginAPI.ashx',
            data: {
                Tel: username,
                password: password
            },
            method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            // header: {}, // 设置请求的 header
            success: function(res){
                // success
                wx.hideToast();
                console.log('app.js',res);
                var code = res.data.code;
                if(code == 0){
                    console.log('app.js','login success');
                    appInstance.globalData.hasLogin = true;

                    var json = res.data.data[0];
                    wx.setStorageSync('userInfo',json);

                    that.setData({
                        firstLogin: false,
                        isLogin: false,
                        loginError: false
                    });
                    
                }else{
                    console.log('app.js','login error');
                    appInstance.globalData.hasLogin = false;

                    that.setData({
                        firstLogin: false,
                        isLogin: false,
                        loginError: true
                    });
                }
            },
            fail: function() {
                // fail
                console.log('app.js','login error');
                appInstance.globalData.hasLogin = false;

                that.setData({
                    firstLogin: false,
                    isLogin: false,
                    loginError: true
                });
            },
            complete: function() {
                wx.hideToast();
            }
        })
    }else{
        console.log('app.js','login error');
        appInstance.globalData.hasLogin = false;

        that.setData({
            firstLogin: true,
            isLogin: false,
            loginError: false
        });
    }
}
//---------------end



